package com.bestcem.xm.common.core.sql.calculator;

import com.bestcem.xm.common.core.sql.ConditionConstant;
import com.bestcem.xm.common.core.sql.ConditionException;
import com.bestcem.xm.common.core.sql.ConditionProxy;
import com.bestcem.xm.common.core.sql.ParamsProxy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author ming.xue <ming.xue@idiaoyan.com>
 * @desc 等于
 * @date 2021-05-25
 */
@Slf4j
public class EqConditionCalculator extends ConditionCalculator {
    public EqConditionCalculator(ConditionProxy conditionProxy, ParamsProxy paramsProxy) {
        super(conditionProxy, paramsProxy);
    }

    /**
     * 获取支持的数据类型
     */
    @Override
    protected List<String> getSupportedDataTypes() {
        return Arrays.asList(ConditionConstant.FieldTypes.STRING,
                ConditionConstant.FieldTypes.DATETIME,
                ConditionConstant.FieldTypes.NUMBER,
                ConditionConstant.FieldTypes.SELECT,
                ConditionConstant.FieldTypes.LEVEL,
                ConditionConstant.FieldTypes.LABEL,
                ConditionConstant.FieldTypes.ADDRESS);
    }

    /**
     * 获取操作符
     */
    @Override
    protected String getOperator() {
        return ConditionConstant.Operators.EQ;
    }

    /**
     * 具体计算逻辑
     */
    @Override
    protected boolean onCalculate() {
        String dataType = this.conditionProxy.getDataType();
        if (StringUtils.equals(dataType, ConditionConstant.FieldTypes.LEVEL)) {
            return this.onLevelCalculate();
        } else {
            return this.onNormalCalculate();
        }
    }

    private boolean onLevelCalculate() {
        List<Object> values = this.conditionProxy.listValues();
        if (CollectionUtils.isEmpty(values) || values.size() < 1) {
            throw new ConditionException(String.format("condition.value %s illegal", values));
        }

        Object endValue = values.get(values.size() - 1);
        if (endValue == null) {
            String msg = String.format("condition.value missing for level, endValue: %s", endValue);
            throw new ConditionException(msg);
        }

        // 参数校验
        Object paramValue = this.getParamValue();
        if (ObjectUtils.isEmpty(paramValue)) {
            return this.getDefaultResult();
        }
        return Objects.equals(endValue, paramValue);
    }

    private boolean onNormalCalculate() {
        Object conditionValue = this.conditionProxy.getValue();
        Object paramValue = this.getParamValue();

        // 参数校验
        if (ObjectUtils.isEmpty(paramValue)) {
            return this.getDefaultResult();
        }

        return Objects.equals(conditionValue, paramValue);
    }
}
